package com.zzx.boot.handler;

import com.google.gson.Gson;
import com.zzx.boot.constant.GlobalEnum;
import com.zzx.boot.utils.R;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author tan
 * @version 1.0
 * @date 2023/7/9 13:54
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Resource
    private Gson gson;
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf8");
        String json = gson.toJson(R.error(GlobalEnum.ACCESSDENIED_HANDLER));
        response.setContentLength(json.getBytes().length);// 告诉浏览器传递过去的数据大小
        PrintWriter writer = response.getWriter();
        writer.println(json);
    }
}
